package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.support.design.widget.BottomSheetBehavior;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.google.android.flexbox.FlexboxLayout;
import com.hitomi.glideloader.GlideImageLoader;
import com.hitomi.tilibrary.style.progress.ProgressPieIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.iflytek.cloud.InitListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.ui.RecognizerDialog;
import com.iflytek.cloud.ui.RecognizerDialogListener;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.adapter.LabelListViewAdapter;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.bean.Video;
import com.shenyue.nbtownlet.databinding.ActivityWaitTaskDetailBinding;
import com.shenyue.nbtownlet.databinding.ChoiceOfPersonnelBinding;
import com.shenyue.nbtownlet.databinding.ImagePartItemRemoveBinding;
import com.shenyue.nbtownlet.databinding.SnapShotSheetDialogBinding;
import com.shenyue.nbtownlet.databinding.VideoPartItemBinding;
import com.shenyue.nbtownlet.databinding.VideoPartItemRemoveBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppInsertTaskModel;
import com.shenyue.nbtownlet.model.AppLoginModel;
import com.shenyue.nbtownlet.model.AppModel;
import com.shenyue.nbtownlet.model.AppTaskModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.model.FileUploadModel;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.StringUtil;
import com.trycatch.mysnackbar.Prompt;
import com.trycatch.mysnackbar.TSnackbar;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerController;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * 待办任务操作
 */

public class WaitTaskDetailActivity extends BaseActivity implements View.OnClickListener, BaseListener {
    private ActivityWaitTaskDetailBinding binding;
    private Transferee transferee;
    private List<ImageView> mList = new ArrayList<>();
    private List<String> mImages = new ArrayList<>();
    private Context mContext;
    private Handler mHandler = new Handler();
    private int[] wh;
    private List<ImageView> afterImages = new ArrayList<>();
    private List<String> afterList = new ArrayList<>();
    private List<Video> afterMoive = new ArrayList<>();
    private static final int REQUEST_CODE_SELECT = 100;
    private static final int REQUEST_CODE_VIDEO = 201;
    private JSONObject dataSource;
    private JSONObject flowData;
    private JSONObject configData;
    private TSnackbar snackBar;
    private List<RadioButton> mRadioButtons = new ArrayList<>();

    // 语音听写UI
    private RecognizerDialog mIatDialog;
    private SnapShotSheetDialogBinding snapShotSheetDialogBinding;
    private final static int CHOICEPERSONNELAREA = 0x401;
    private List<ChoiceOfPersonnelBinding> choiceOfPersonnelList = new ArrayList<>();
    private ChoiceOfPersonnelBinding selectChoiceOfPersonnelBinding = null;
    private boolean isLoading = false;
    private BottomSheetDialog sheetDialog;
    private String action_type;
    private JSONArray flowSendData;
    private SimpleDateFormat format0 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);

    private boolean imageLoading = false;
    private boolean videoLoading = false;
    private int videoPosition = 0;
    private int imagePosition = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_wait_task_detail);
        Bundle bundle = getIntent().getExtras();
        dataSource = JSON.parseObject(bundle.getString(DefaultModel.PAGE_DATA));
        setActionBar(true, dataSource.getString("Title"));

        mContext = this;
        transferee = Transferee.getDefault(mContext);

        wh = DensityUtil.getWH(this, 2, 24);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(wh[0], wh[1]);
        binding.btnPhoto.setLayoutParams(layoutParams);
        binding.btnPhoto.setOnClickListener(this);
        binding.btnVideo.setLayoutParams(layoutParams);
        binding.btnVideo.setOnClickListener(this);

        binding.btnSaveL.setVisibility(View.GONE);
        binding.btnSendL.setVisibility(View.GONE);
        binding.btnBackL.setVisibility(View.GONE);
        binding.btnCompleteL.setVisibility(View.GONE);
        binding.btnSave.setOnClickListener(this);
        binding.btnSend.setOnClickListener(this);
        binding.btnBack.setOnClickListener(this);
        binding.btnComplete.setOnClickListener(this);
        binding.btnVoice.setOnClickListener(this);
        binding.AFTERIDEA.setParentScrollView(binding.scrollView);

        binding.score.setItems("0", "1", "2", "3");

        snapShotSheetDialogBinding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.snap_shot_sheet_dialog, null, false);
        snapShotSheetDialogBinding.btnCancel.setOnClickListener(new SendClickListener());
        snapShotSheetDialogBinding.btnSubmit.setOnClickListener(new SendClickListener());
        sheetDialog = new BottomSheetDialog(this);
        sheetDialog.setContentView(snapShotSheetDialogBinding.getRoot());
        sheetDialog.setCancelable(false);
        sheetDialog.setCanceledOnTouchOutside(false);
        BottomSheetBehavior mDialogBehavior = BottomSheetBehavior.from((View)snapShotSheetDialogBinding.getRoot().getParent());
        if(mDialogBehavior != null) {
            mDialogBehavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            mDialogBehavior.setPeekHeight(DensityUtil.dip2px(mContext, 1000));
        }

        /*********讯飞语音输入*******/
        // 初始化听写Dialog，如果只使用有UI听写功能，无需创建SpeechRecognizer
        // 使用UI听写功能，请根据sdk文件目录下的notice.txt,放置布局文件和图片资源
        mIatDialog = new RecognizerDialog(this, mInitListener);
        // 设置听写引擎
        mIatDialog.setParameter(SpeechConstant.ENGINE_TYPE, SpeechConstant.TYPE_CLOUD);

        snackBar = showTSnackbar("正在查询数据..., 请稍候");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                findDetail();
            }
        }, 32);
    }

    private void findDetail() {
        JSONObject param = new JSONObject();
        param.put("id", dataSource.getString("InstanceID"));
        AppInsertTaskModel.getDetailWorkByID(mContext, param, this);
    }

    private void initView() {
        binding.TASKCODE.setText(StringUtil.getValue(flowData.getString("CODE")));
        binding.TITILE.setText(StringUtil.getValue(flowData.getString("TITILE")));
        binding.TADDRESS.setText(StringUtil.getValue(flowData.getString("TADDRESS")));
        binding.ASSESSTASKNAME.setText(StringUtil.getValue(flowData.getString("ASSESSTASKNAME")));
        binding.ASSESSTYPENAME.setText(StringUtil.getValue(flowData.getString("ASSESSTYPENAME")));
        binding.AFTERIDEA.setText(StringUtil.getValue(flowData.getString("AFTERIDEA")));
        binding.score.setSelectedIndex(Integer.valueOf(flowData.getString("SCORE")));
        binding.PROBLEM.setText(StringUtil.getValue(flowData.getString("PROBLEM")));
        String CREATETIME = StringUtil.getValue(flowData.getString("CREATETIME"));
        if (CREATETIME.contains("T"))
            CREATETIME = CREATETIME.substring(0, CREATETIME.indexOf("T"));
        binding.CREATETIME.setText(CREATETIME);
        binding.CREATORNAME.setText(StringUtil.getValue(flowData.getString("CREATORNAME")));
        binding.ASSESSMENTNAME.setText(StringUtil.getValue(flowData.getString("ASSESSMENTNAME")));

        resetQuestionImages();
        resetQuestionVideos();

        String AFTERIMAGES = flowData.getString("AFTERIMAGES");
        if (!StringUtil.isNull(AFTERIMAGES)) {
            String[] args = AFTERIMAGES.split(",");
            for (int i = 0, j = args.length; i < j; i++) {
                afterList.add(args[i]);
            }
            resetPhotos();
        }
        String AFTERMOIVE = flowData.getString("AFTERMOIVE");
        if (!StringUtil.isNull(AFTERMOIVE)) {
            String[] args = AFTERMOIVE.split(",");
            for (int i = 0, j = args.length; i < j; i++) {
                afterMoive.add(new Video("", "", args[i]));
            }
            resetVideos();
        }
    }

    private void initConfig() {
        List<String> buttons = AppTaskModel.getButtons(mContext, configData);
        if (buttons.contains(AppTaskModel.BTN_SAVE))
            binding.btnSaveL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_SEND))
            binding.btnSendL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_BACK))
            binding.btnBackL.setVisibility(View.VISIBLE);
        if (buttons.contains(AppTaskModel.BTN_COMPLETED))
            binding.btnCompleteL.setVisibility(View.VISIBLE);
    }

    private void resetQuestionImages() {
        String IMAGEADDRESS = StringUtil.getValue(flowData.getString("IMAGEADDRESS"));
        if (StringUtil.isNull(IMAGEADDRESS))
            return;
        String[] array = IMAGEADDRESS.split(",");
        for (int i = 0, j = array.length; i < j; i++) {
            mImages.add(array[i]);
        }
        binding.questionImage.removeAllViews();
        for (int i = 0; i < mImages.size(); i++) {
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
            ImageView imageView = new ImageView(mContext);
            imageView.setId(i);
            imageView.setLayoutParams(layoutParams);
            imageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    TransferConfig config = TransferConfig.build()
                            .setNowThumbnailIndex(v.getId())
                            .setSourceImageList(mImages)
                            .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                            .setOriginImageList(mList)
                            .setProgressIndicator(new ProgressPieIndicator())
                            .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                            .create();
                    transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                        @Override
                        public void onShow() {
                            Glide.with(mContext).pauseRequests();
                        }

                        @Override
                        public void onDismiss() {
                            Glide.with(mContext).resumeRequests();
                        }
                    });
                }
            });
            binding.questionImage.addView(imageView);
            mList.add(imageView);
            GlideUtil.loadImgCenterCrop(mContext, mImages.get(i), imageView);
        }
    }

    private void resetQuestionVideos() {
        String MOIVEADDRESS = StringUtil.getValue(flowData.getString("MOIVEADDRESS"));
        if (StringUtil.isNull(MOIVEADDRESS))
            return;
        List<Video> videoList = new ArrayList<>();
        String[] array = MOIVEADDRESS.split(",");
        for (int i = 0, j = array.length; i < j; i++) {
            videoList.add(new Video("", "", array[i]));
        }
        binding.questionVideo.removeAllViews();
        for (int i = 0, j = videoList.size(); i < j; i++) {
            binding.questionVideo.addView(getVideoPartItemBinding(videoList.get(i)));
        }
    }

    private View getVideoPartItemBinding(Video video) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        VideoPartItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.video_part_item, null, false);
        binding.niceVideoPlayer.setPlayerType(NiceVideoPlayer.PLAYER_TYPE_IJK); // or NiceVideoPlayer.PLAYER_NATIVE
        binding.niceVideoPlayer.setUp(video.getVideoUrl(), null);
        NiceVideoPlayerController mController = new NiceVideoPlayerController(mContext);
        mController.setTitle(video.getTitle());
        mController.setImage(video.getImageUrl());
        binding.niceVideoPlayer.setController(mController);
        View view = binding.getRoot();
        view.setLayoutParams(layoutParams);

        return view;
    }

    private View getVideoPartItemRemoveBinding(final Video video) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        VideoPartItemRemoveBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.video_part_item_remove, null, false);
        binding.niceVideoPlayer.setPlayerType(NiceVideoPlayer.PLAYER_TYPE_IJK); // or NiceVideoPlayer.PLAYER_NATIVE
        binding.niceVideoPlayer.setUp(video.getVideoUrl(), null);
        NiceVideoPlayerController mController = new NiceVideoPlayerController(mContext);
        mController.setTitle(video.getTitle());
        mController.setImage(video.getImageUrl());
        binding.niceVideoPlayer.setController(mController);
        View view = binding.getRoot();
        view.setLayoutParams(layoutParams);
        binding.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                afterMoive.remove(video);
                resetVideos();
            }
        });

        return view;
    }

    private View getImagePartItemRemoveBinding(final String url, int id) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        ImagePartItemRemoveBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.image_part_item_remove, null, false);
        View view = root.getRoot();
        view.setLayoutParams(layoutParams);
        root.btnRemove.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                afterList.remove(url);
                resetPhotos();
            }
        });
        root.image.setId(id);
        root.image.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TransferConfig config = TransferConfig.build()
                        .setNowThumbnailIndex(v.getId())
                        .setSourceImageList(afterList)
                        .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                        .setOriginImageList(afterImages)
                        .setProgressIndicator(new ProgressPieIndicator())
                        .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                        .create();
                transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                    @Override
                    public void onShow() {
                        Glide.with(mContext).pauseRequests();
                    }

                    @Override
                    public void onDismiss() {
                        Glide.with(mContext).resumeRequests();
                    }
                });
            }
        });
        afterImages.add(root.image);
        GlideUtil.loadImgCenterCrop(mContext, url, root.image);

        return view;
    }

    private void resetPhotos() {
        afterImages.clear();
        View btnPhoto = binding.rectifyImage.getChildAt(binding.rectifyImage.getChildCount() - 1);
        binding.rectifyImage.removeAllViews();
        for (int i = 0, j = afterList.size(); i < j; i++) {
            binding.rectifyImage.addView(getImagePartItemRemoveBinding(afterList.get(i), i));
        }
        binding.rectifyImage.addView(btnPhoto);
    }

    private void resetVideos() {
        View btnVideo = binding.rectifyVideo.getChildAt(binding.rectifyVideo.getChildCount() - 1);
        binding.rectifyVideo.removeAllViews();
        for (int i = 0, j = afterMoive.size(); i < j; i++) {
            binding.rectifyVideo.addView(getVideoPartItemRemoveBinding(afterMoive.get(i)));
        }
        binding.rectifyVideo.addView(btnVideo);
    }

    @Override
    public void onDestroy() {
        if (transferee != null)
            transferee.destroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) {
            return;
        }
        doCancel();
    }

    @Override
    public void onClick(View view) {
        if (isLoading)
            return;
        switch (view.getId()) {
            case R.id.btn_photo:
                doPhoto();
                break;
            case R.id.btn_video:
                doVideo();
                break;
            case R.id.btn_voice:
                doVoice();
                break;
            case R.id.btn_send: {
                action_type = "submit";
                onSave();
                break;
            }
            case R.id.btn_save: {
                action_type = "save";
                onSave();
                break;
            }
            case R.id.btn_complete: {
                action_type = "Completed";
                onComplete();
                break;
            }
            case R.id.btn_back: {
                action_type = "back";
                onBack();
                break;
            }
        }
    }

    private void doPhoto() {
        MultiImageSelector.create()
                .showCamera(true) // show camera or not. true by default
                .count(9) // max select image size, 9 by default. used width #.multi()
                .multi() // multi mode, default mode;
                .start(this, REQUEST_CODE_SELECT);
    }

    private void doVideo() {
        Intent intent = new Intent(mContext, VideoActivity.class);
        startActivityForResult(intent, REQUEST_CODE_VIDEO);
    }

    private void doVoice() {
        // 显示听写对话框
        mIatDialog.setListener(mRecognizerDialogListener);
        mIatDialog.show();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_SELECT) {
            List<String> images = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
            for (int i = 0, j = images.size(); i < j; i++) {
                String item = images.get(i);
                if (!this.afterList.contains(item))
                    this.afterList.add(item);
            }
            resetPhotos();
        } else if (resultCode == RESULT_OK && data != null && requestCode == REQUEST_CODE_VIDEO) {
            String url = data.getStringExtra("url");
            this.afterMoive.add(new Video("", "", url));
            resetVideos();
        } else if (resultCode == RESULT_OK && data != null && requestCode == CHOICEPERSONNELAREA) {
            String val = data.getStringExtra(DefaultModel.PAGE_DATA);
            LabelListViewAdapter listViewAdapter = (LabelListViewAdapter) selectChoiceOfPersonnelBinding.personnelList.getAdapter();
            listViewAdapter.clear();
            listViewAdapter.addItems(JSON.parseArray(val));
        }
    }

    @Override
    public void success(String val, String action) {
        if (AppInsertTaskModel.GETDETAILWORKBYID_ACTION.equals(action)) {
            flowData = JSON.parseObject(val);
            initView();
            JSONObject param = new JSONObject();
            param.put("userID", AppLoginModel.getIdentityId(mContext));
            param.put("flowid", dataSource.getString("FlowID"));
            param.put("formid", dataSource.getString("FormID"));
            param.put("instanceid", dataSource.getString("InstanceID"));
            param.put("stepid", dataSource.getString("StepID"));
            param.put("groupid", dataSource.getString("GroupID"));
            param.put("taskID", dataSource.getString("ID"));
            AppTaskModel.WaitListDetail(mContext, param, this);
        } else if (AppTaskModel.WAITLIST_DETAIL_ACTION.equals(action)) {
            hideTSnackbar(snackBar, "数据查询成功");
            configData = JSON.parseObject(val);
            initConfig();
        } else if (AppInsertTaskModel.UPDATESSDATA_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("true".equals(data.getString("IsSuccess"))) {
                if ("save".equals(action_type)) {//调用流程 Execute方法
                    hideTSnackbar(snackBar, "信息保存成功");
                    AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                    builder.setTitle("信息提交成功");
                    builder.setMessage("信息保存成功");
                    builder.setCancelable(false);
                    builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            setResult(RESULT_OK);
                            finish();
                        }
                    });
                    builder.show();
                } else if ("submit".equals(action_type)) {//调用流程 FlowSend方法
                    FlowSend();
                }
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, "信息提交失败，相应参数有错", Prompt.WARNING);
            }
        } else if (AppTaskModel.WAITLIST_EXECUTE_ACTION.equals(action)) {
            JSONObject data = JSON.parseObject(val);
            if ("true".equals(data.getString("IsSuccess"))) {
                hideTSnackbar(snackBar, data.getString("Messages"));
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("信息提交成功");
                builder.setMessage(data.getString("Messages"));
                builder.setCancelable(false);
                builder.setPositiveButton("我知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
                builder.show();
            } else {
                isLoading = false;
                hideTSnackbar(snackBar, data.getString("Message"), Prompt.WARNING);
            }
        } else if (AppTaskModel.WAITLIST_FLOWSEND_ACTION.equals(action) || AppTaskModel.WAITLIST_FLOWBACK_ACTION.equals(action)) {
            hideTSnackbar(snackBar, "请选择流程对应的人员");
            mRadioButtons.clear();
            flowSendData = JSON.parseArray(val);
            choiceOfPersonnelList.clear();
            snapShotSheetDialogBinding.flowSend.removeAllViews();
            for (int i = 0; i < flowSendData.size(); i++) {
                ChoiceOfPersonnelBinding root = getChoiceOfPersonnelBinding(flowSendData.getJSONObject(i));
                choiceOfPersonnelList.add(root);
                snapShotSheetDialogBinding.flowSend.addView(root.getRoot());
            }
            sheetDialog.show();
        } else if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            if (imageLoading) {
                JSONObject data = JSON.parseObject(val);
                String AFTERIMAGES = flowData.getString("AFTERIMAGES");
                StringBuilder sb = new StringBuilder();
                if (!StringUtil.isNull(AFTERIMAGES))
                    sb.append(AFTERIMAGES).append(",").append(data.getString("FullUrl")).append(",");
                else
                    sb.append(data.getString("FullUrl")).append(",");
                if (sb.lastIndexOf(",") != -1)
                    sb.deleteCharAt(sb.lastIndexOf(","));
                flowData.put("AFTERIMAGES", sb.toString());

                if ((imagePosition + 1) >= afterList.size()) {
                    imageLoading = false;
                    if (!afterMoive.isEmpty()) {
                        videoLoading = true;
                        FileUploadModel.upload(mContext, afterMoive.get(videoPosition).getVideoUrl(), false, this);
                        return;
                    }
                    AppInsertTaskModel.UpdatessData(mContext, flowData, this);
                } else {
                    imagePosition++;
                    FileUploadModel.upload(mContext, afterList.get(imagePosition), true, this);
                }
            } else if (videoLoading) {
                JSONObject data = JSON.parseObject(val);
                String AFTERMOIVE = flowData.getString("AFTERMOIVE");
                StringBuilder sb = new StringBuilder();
                if (!StringUtil.isNull(AFTERMOIVE))
                    sb.append(AFTERMOIVE).append(",").append(data.getString("FullUrl")).append(",");
                else
                    sb.append(data.getString("FullUrl")).append(",");
                if (sb.lastIndexOf(",") != -1)
                    sb.deleteCharAt(sb.lastIndexOf(","));
                flowData.put("AFTERMOIVE", sb.toString());

                if ((videoPosition + 1) >= afterMoive.size()) {
                    videoLoading = false;
                    AppInsertTaskModel.UpdatessData(mContext, flowData, this);
                } else {
                    videoPosition++;
                    FileUploadModel.upload(mContext, afterMoive.get(videoPosition).getVideoUrl(), false, this);
                }
            }
        } else if (AppTaskModel.WAITLIST_COMFIRMCOMPLETE_ACTION.equals(action)) {
            JSONArray array = JSON.parseArray(val);
            JSONObject data = array.getJSONObject(0);
            final String ctype = data.getString("ctype");
            if ("-1".equals(ctype)) {
                AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
                builder.setTitle("信息提交成功");
                builder.setMessage(data.getString("msg"));
                builder.setCancelable(false);
                builder.setPositiveButton("继续提交", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Execute(new JSONArray(), "", ctype);
                    }
                });
                builder.setNegativeButton("完成", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        setResult(RESULT_OK);
                        finish();
                    }
                });
                builder.show();
            } else {
                Execute(new JSONArray(), "", ctype);
            }
        }
    }

    @Override
    public void error(String error, String action) {
        if (FileUploadModel.SMALLTOWN_XCZFILEUPLOAD_SAVEFILE_ACTION.equals(action)) {
            imageLoading = false;
            videoLoading = false;
            FileUploadModel.stop();
            AppInsertTaskModel.UpdatessData(mContext, flowData, this);
            return;
        }

        isLoading = false;
        hideTSnackbar(snackBar, error, Prompt.WARNING);
    }

    private void printResult(RecognizerResult results, boolean isLast) {
        String result = StringUtil.parseIatResult(results.getResultString());
        int index = binding.AFTERIDEA.getSelectionStart();//获取光标所在位置
        Editable edit = binding.AFTERIDEA.getEditableText();
        if (index < 0 || index >= edit.length()) {
            edit.append(result);
        } else {
            edit.insert(index, result);//光标所在位置插入文字
        }
    }

    private void onSave() {
        imageLoading = false;
        videoLoading = false;
        videoPosition = 0;
        imagePosition = 0;

        flowData.put("EDITID", AppLoginModel.getUserId(mContext));
        flowData.put("EDITIDENTITY", AppLoginModel.getIdentityId(mContext));
        flowData.put("EDITNAME", AppLoginModel.getUserName(mContext));
        flowData.put("EDITTIME", format0.format(new Date()));

        flowData.put("SCORE", StringUtil.getValue(binding.score.getText()));//扣分分值
        flowData.put("AFTERIDEA", binding.AFTERIDEA.getText().toString().trim());//整改意见
        flowData.put("AFTERIMAGES", "");//整改后图片地址
        flowData.put("AFTERMOIVE", "");//整改后视频地址
        isLoading = true;
        snackBar = showTSnackbar("正在提交信息..., 请稍候");

        if (!afterList.isEmpty()) {
            imageLoading = true;
            FileUploadModel.upload(mContext, afterList.get(imagePosition), true, this);
            return;
        }

        if (!afterMoive.isEmpty()) {
            videoLoading = true;
            FileUploadModel.upload(mContext, afterMoive.get(videoPosition).getVideoUrl(), false, this);
            return;
        }
        if (imageLoading || videoLoading)
            return;

        AppInsertTaskModel.UpdatessData(mContext, flowData, this);
    }

    private void onComplete() {
        isLoading = true;
        snackBar = showTSnackbar("正在提交信息..., 请稍候");
        JSONObject param = new JSONObject();
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("flowid", dataSource.getString("FlowID"));
        param.put("formid", dataSource.getString("FormID"));
        param.put("instanceid", dataSource.getString("InstanceID"));
        param.put("stepid", dataSource.getString("StepID"));
        param.put("groupid", dataSource.getString("GroupID"));
        param.put("taskID", dataSource.getString("ID"));

        AppTaskModel.WaitListComfirmComplete(mContext, param, this);
    }

    private void onBack() {
        isLoading = true;
        snackBar = showTSnackbar("正在提交信息..., 请稍候");
        JSONObject param = new JSONObject();
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("flowid", dataSource.getString("FlowID"));
        param.put("formid", dataSource.getString("FormID"));
        param.put("instanceid", dataSource.getString("InstanceID"));
        param.put("stepid", dataSource.getString("StepID"));
        param.put("groupid", dataSource.getString("GroupID"));
        param.put("taskID", dataSource.getString("ID"));

        AppTaskModel.WaitListFlowBack(mContext, param, this);
    }

    private void Execute(JSONArray steps, String comment, String ctype) {
        JSONObject param = new JSONObject();
        param.put("flowid", configData.getString("flowid"));
        param.put("instanceid", dataSource.getString("InstanceID"));
        param.put("stepid", configData.getString("stepid"));
        param.put("taskid", configData.getString("taskid"));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("Formid", dataSource.getString("FormID"));
        param.put("issign", StringUtil.isNull(configData.getString("issign")) ? "0" : configData.getString("issign"));
        param.put("comment", comment);
        param.put("taskname", flowData.getString("TITILE"));
        if ("back".equals(action_type))
            param.put("groupid", dataSource.getString("GroupID"));
        else
            param.put("groupid", AppModel.GROUPID);
        param.put("ctype", ctype);
        JSONObject params = new JSONObject();
        params.put("type", action_type);
        params.put("steps", steps == null ? "" : steps);
        param.put("params1", params.toString());
        AppTaskModel.WaitListExecute(mContext, param, this);
    }

    private void FlowSend() {
        JSONObject param = new JSONObject();
        param.put("areaid", flowData.getString("STREETID"));
        param.put("instanceid", dataSource.getString("InstanceID"));
        param.put("stepid", configData.getString("stepid"));
        param.put("taskid", configData.getString("taskid"));
        param.put("userID", AppLoginModel.getIdentityId(mContext));
        param.put("tasktype", configData.getString("signType"));
        param.put("flowid", configData.getString("flowid"));
        param.put("groupid", AppModel.GROUPID);
        AppTaskModel.WaitListFlowSend(mContext, param, this);
    }

    private ChoiceOfPersonnelBinding getChoiceOfPersonnelBinding(final JSONObject data) {
        final ChoiceOfPersonnelBinding root = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.choice_of_personnel, null, false);
        root.radio.setText(StringUtil.isNull(data.getString("stepname")) ? data.getString("name") : data.getString("stepname"));
        root.radio.setChecked("1".equals(data.getString("ischeck")));
        if ("submit".equals(action_type)) {
            root.btnArea.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    selectChoiceOfPersonnelBinding = root;
                    Bundle bundle = new Bundle();
                    bundle.putString(DefaultModel.PAGE_DATA, "0");
                    bundle.putString("selectRang", data.getString("selectRang"));
                    bundle.putString("Isfilt", data.getString("isfilt"));
                    bundle.putString("STREETID", flowData.getString("STREETID"));
                    toActivityForResult(ChoicePersonnelActivity.class, bundle, CHOICEPERSONNELAREA);
                }
            });
        } else
            root.btnArea.setVisibility(View.GONE);
        root.radio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for (int i = 0; i < mRadioButtons.size(); i++) {
                    RadioButton rad = mRadioButtons.get(i);
                    if(rad == root.radio){
                        rad.setChecked(true);
                    }else{
                        rad.setChecked(false);
                    }
                }
            }
        });
        mRadioButtons.add(root.radio);
        LabelListViewAdapter listViewAdapter = new LabelListViewAdapter(mContext);
        root.personnelList.setAdapter(listViewAdapter);
        root.personnelList.setParentScrollView(snapShotSheetDialogBinding.scrollView);
        View view = root.getRoot();
        view.setTag(data.toString());
        return root;
    }

    /**
     * 初始化监听器。
     */
    private InitListener mInitListener = new InitListener() {
        @Override
        public void onInit(int code) {
        }
    };

    /**
     * 听写UI监听器
     */
    private RecognizerDialogListener mRecognizerDialogListener = new RecognizerDialogListener() {
        public void onResult(RecognizerResult results, boolean isLast) {
            printResult(results, isLast);
        }

        /**
         * 识别回调错误.
         */
        public void onError(SpeechError error) {
        }
    };

    private class SendClickListener implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_cancel: {//取消
                    sheetDialog.hide();
                    isLoading = false;
                    break;
                }
                case R.id.btn_submit: {//提交
                    //步骤及人员信息字典数组
                    JSONArray array = new JSONArray();
                    for (int i = 0, j = flowSendData.size(); i < j; i++) {
                        final JSONObject flow = flowSendData.getJSONObject(i);
                        ChoiceOfPersonnelBinding root = choiceOfPersonnelList.get(i);
                        if(!root.radio.isChecked())
                            continue;
                        LabelListViewAdapter listViewAdapter = (LabelListViewAdapter) root.personnelList.getAdapter();
                        JSONArray items = listViewAdapter.getItems();
                        final StringBuilder sb = new StringBuilder();
                        for (int k = 0, h = items.size(); k < h; k++) {
                            JSONObject item = items.getJSONObject(k);
                            sb.append(item.getString("ID")).append(",");
                        }
                        if (sb.lastIndexOf(",") != -1)
                            sb.deleteCharAt(sb.lastIndexOf(","));
                        if(StringUtil.isNull(sb.toString()) && root.btnArea.getVisibility() == View.VISIBLE){
                            Toast.makeText(mContext, "请选择流程步骤对应的人员", Toast.LENGTH_LONG).show();
                            return;
                        }
                        array.add(new JSONObject() {{
                            put("id", StringUtil.isNull(flow.getString("stepid")) ? flow.getString("id") : flow.getString("stepid"));
                            put("member", StringUtil.isNull(sb.toString()) ? "" : sb.toString());
                        }});
                    }
                    if (array.isEmpty()) {
                        Toast.makeText(mContext, "请选择流程步骤", Toast.LENGTH_LONG).show();
                        return;
                    }
                    sheetDialog.hide();
                    snackBar = showTSnackbar("正在提交数据..., 请稍候");
                    Execute(array, snapShotSheetDialogBinding.comment.getText().toString().trim(), "");
                    break;
                }
            }
        }
    }

    private void doCancel() {
        String msg = "数据尚未提交，您确定要退出吗？";
        if (isLoading)
            msg = "数据正在提交，您确定要退出吗？";
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("温馨提示")
                .setMessage(msg)
                .setPositiveButton("点错了", null)
                .setNegativeButton("退出", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        FileUploadModel.stop();
                        dialogInterface.dismiss();
                        finish();
                    }
                });
        builder.create().show();
    }
}
